
/******************************************************************************
*
* Freescale Semiconductor Inc.
* (c) Copyright 2011-2012 Freescale Semiconductor, Inc.
* ALL RIGHTS RESERVED.
*
*******************************************************************************
*
* @file Lab_demo.c
*
* @author a13984
*
* @version 0.0.1
*
* @date Jul-15-2011
*
* @brief providing framework of test cases for MCU. 
*
*******************************************************************************/

#include "common.h"
#include "rtc.h"
#include "pit.h"
#include "irda.h"
#include "mma8451_test.h"
#include "angle_cal.h"
#include "led.h"
#include "uart.h"
#include "key.h"
#include "math.h"
#include "mscan.h"
#include "mscan_api.h"
#include "sysinit.h"
/******************************************************************************
* Global variables
******************************************************************************/

/******************************************************************************
* Constants and macros
******************************************************************************/
#define NODE_ID1			0x801
#define NODE_ID2			0x802
#define NODE_ID3			0x803

#define CAN_IDAR0			NODE_ID1
#define CAN_IDAR1			0xFFFFFFFF
#define CAN_IDMR0			0xFFFFFFFF
#define CAN_IDMR1			0xFFFFFFFF

#define ASLIDER_DELAY_TIMER		    50
//#define TSI_RELEASE                 0x01
//#define TSI_TOUCH                   0x02
#define OVER_TIME_COUNT             3
//#define TSI_THRESHOLD               500
/******************************************************************************
* Local types
******************************************************************************/

/******************************************************************************
* Local function prototypes
******************************************************************************/
extern void IrDA_Init( void );
/******************************************************************************
* Local variables
******************************************************************************/
DemoStateType DemoState = DemoRTC;
uint8_t u8LedControlMode = 0;
uint8_t u8CurrentDemoState;
uint8_t u8DemoModeUpdatedDelay = 0;


uint8_t u8OneSecondFlag = 0;
signed int pre_i16Angle_xy = 0;

uint8_t u8ShakeCnt = 0;

uint8_t u8BoardIdleCnt = 0;

/******************************************************************************
* Local functions
******************************************************************************/
int main (void);
void RTC_Task(void);
void Pit0CallBack( void );

void RTC_Task(void)
{
    DisableInterrupts;

    u8OneSecondFlag = 1;

    if (DemoState == DemoRTC)
    {
        //toggle Green Led to indicate Demo mode is DemoRTC now.
        LED1_Toggle();
        LED_Set_Light(LED_Red, 0);
        LED_Set_Light(LED_Blue, 0);

        if ((i16Angle_yz/100 != 0) && (i16Angle_xz/100 != 0))
        {
            DemoState = DemoMMA8451;
            LED1_Off();
            LED_Set_Light(LED_Red, 0);
            LED_Set_Light(LED_Blue, 0);
            printf("\r\nNow is MMA8451 Demo, the lightness of blue LED is changed according to the board position. \r\n");
        }
    }
    else
    {
        //In other Demo mode
    	if ((i16Angle_yz/100 == 0) && (i16Angle_xz/100 == 0))
    	{
            //MMA8451 detect if FRDM board is placed  (no key input && lay flat for 5s)
            u8BoardIdleCnt ++;

            if (u8BoardIdleCnt >=9)
            {
                DemoState = DemoRTC;
                LED_Set_Light(LED_Red, 0);
                LED_Set_Light(LED_Blue, 0);
                u8BoardIdleCnt  = 0;
                printf("\r\nNow is RTC Demo, the Green LED is toggled every 1 second. \r\n");

            }
        }
        else
        {
        	u8BoardIdleCnt = 0;
        }
    }
    
	EnableInterrupts;

}

/*****************************************************************************//*!
*
* @brief callback routine of PIT0 driver which does what you want to do at 
*        every PIT0 period.
*        
* @param  none
*
* @return none
*
* @ Pass/ Fail criteria: none
*****************************************************************************/
void Pit0CallBack( void )
{
    //Read mma8451 every 100ms
    //LED0_Toggle();
	AccelRead();    
}



void delay(unsigned int delay_value)
{
    unsigned int i, j, k;

    for (i=0; i<delay_value; i++)
    {
        for (j=0; j<0xF; j++)
            for (k=0; k<0xFFFF; k++)
            {
                __ASM volatile("nop");
            }
    }
}
void LED_Test(void)
{
    uint8_t i;

    delay(10);
    
	LED0_Init();
	LED1_Init();
	LED2_Init();


    for (i = 0; i<3; i++)
    {
        if (i%3 == 0)
        {
            LED0_On();
            LED1_Off();
            LED2_Off();
        }
        else if (i%3 == 1)
        {
            LED0_Off();
            LED1_On();
            LED2_Off();
        }
        else
        {
            LED0_Off();
            LED1_Off();
            LED2_On();
        }
        delay(10);
    }

    LED0_On();
    LED1_On();
    LED2_On();

    delay(10);

    LED0_Off();
    LED1_Off();
    LED2_Off();

    delay(10);

}
/******************************************************************************
* Global functions
******************************************************************************/
extern void UART_InitPrint(void);

void CAN_Test(void)
{
    MSCAN_ConfigType sMSCANConfig = {0};
    ItemInfoType     sCANTxItemInfo;
    MSCAN_FrameType  sRxFrameInfo;
    uint8_t i;

    printf("\nRunning the KE06 CAN Test.\n");

    LED0_Off();
    LED1_Off();
    LED2_Off();
    
    MSCAN_GlobeVaribleInit(MSCAN);
    
    SIM->PINSEL1 |= SIM_PINSEL1_MSCANPS_MASK;
    
    sMSCANConfig.sBaudRateSetting.SJW = BAUD_RATE_SJW;
    sMSCANConfig.sBaudRateSetting.BRP = BAUD_RATE_BRP;
    sMSCANConfig.sBaudRateSetting.SAMP = BAUD_RATE_SAMP;
	sMSCANConfig.sBaudRateSetting.TSEG1= BAUD_RATE_TSEG1;
	sMSCANConfig.sBaudRateSetting.TSEG2= BAUD_RATE_TSEG2;
	sMSCANConfig.u32IDAR0 = CAN_IDAR0;
	sMSCANConfig.u32IDAR1 = CAN_IDAR1;
	sMSCANConfig.u32IDMR0 = CAN_IDMR0;
	sMSCANConfig.u32IDMR1 = CAN_IDMR1;
	sMSCANConfig.u8IDARMode = ID_ACCEPT_MODE_TWO32;
	sMSCANConfig.sSetting.bCanEn = 1;
    sMSCANConfig.sSetting.bCLKSRC = 1;
  //  sMSCANConfig.sSetting.bLoopModeEn = 1;
	sMSCANConfig.sSetting.bRxFullIEn=1;
	sMSCANConfig.sSetting.bTimerEn=1;
	sMSCANConfig.sSetting.bOverRunIEn=1;
	sMSCANConfig.sSetting.bStatusChangeIEn=1;
//	sMSCANConfig.sSetting.bTxEmptyIEn=1;
	CAN_Init(MSCAN,&sMSCANConfig);

	//Initialize the Tx information
	sCANTxItemInfo.bIsExtOrStand = 1;
	sCANTxItemInfo.bIsRemoteFrame = 0;
	sCANTxItemInfo.ID_Type.ID = NODE_ID1;
	sCANTxItemInfo.u32DataLength = 8;
	for(i=0;i<22;i++)
	{
		sCANTxItemInfo.u8DataBuff[i] = i;
	}
	sCANTxItemInfo.u8BPR = 0x80;

	CAN_SendItemToBuffer(MSCAN,&sCANTxItemInfo,&sCAN_TxBuff);

    while(1)
    {
        CAN_CheckSendBufferFrame(MSCAN,&sCAN_TxBuff);
        if(CAN_ReadOneFramefromBufferQueue(&sRxFrameInfo))
        {
			printf("receive a frame data!\n");
			printf("ID is 0x%x!\n",sRxFrameInfo.ID_Type);
			printf("Data length is %d\n",sRxFrameInfo.DLR);
			for(i=0;i<sRxFrameInfo.DLR;i++)
			{
				printf("0x%x,",sRxFrameInfo.DSR[i]);
			}
			printf("\n");

            printf("\n\rCAN test success!\n");
            
            break;
        }
        
        delay(1);
        
        //sCANTxItemInfo.u8DataBuff[7]++;
        
        //CAN_SendItemToBuffer(MSCAN,&sCANTxItemInfo,&sCAN_TxBuff);
    } 
}

/*****************************************************************************//*!
*
* @brief 
*        
* @param  none
*
* @return none
*
* @ Pass/ Fail criteria: none
*****************************************************************************/
int main(void)
{
	RTC_ConfigType  sRTCConfig;
    RTC_ConfigType  *pRTCConfig = &sRTCConfig;   
    PIT_ConfigType  sPITConfig0;    
    PIT_ConfigType  *pPIT_Config0   =&sPITConfig0; 

    uint8_t u8Result;

    /* Perform processor initialization */
	sysinit();

    DisableInterrupts;
    
    printf("\n\rFRDM-KE06Z Demo Application\n");

    LED_Test();

	IrDA_Init();
	u8Result = IrDA_Test();
	if( u8Result == 0 )
    {
        printf("\n\rIrDA test success!\n");
    }
    else
    {
        printf("\n\rIrDA test fail, error code is %d!\n", u8Result);
    }

    CAN_Test();
    
    //Init KBI Module for 2 keys
    Key_Init();

	/* initialize IIC and MMA8451 for accerometer test */
	AccelInit();

	//Init Blue/Red LED associated with MMA8451 Demo.
    LED_DriveByFtm();
    LED_Set_Light(LED_Blue, 0);
    LED_Set_Light(LED_Red, 0);

    /* configure RTC to 1Hz interrupt frequency */
    pRTCConfig->u16ModuloValue = 9;                                
    pRTCConfig->bInterruptEn   = RTC_INTERRUPT_ENABLE;     /* enable interrupt */
    pRTCConfig->bClockSource   = RTC_CLKSRC_1KHZ;          /*clock source is 1khz*/
    pRTCConfig->bClockPresaler = RTC_CLK_PRESCALER_100;    /*prescaler is 100*/

    RTC_SetCallback(RTC_Task);
	RTC_Init(pRTCConfig);

	/* initialize PIT - 100ms at 20MHz bus clock */
    pPIT_Config0->u32LoadValue      = (2000000L-1);
    pPIT_Config0->bFreeze           = FALSE;    
    pPIT_Config0->bModuleDis        = FALSE;    /*!< enable PIT module */     
    pPIT_Config0->bInterruptEn      = TRUE;
    pPIT_Config0->bChainMode        = FALSE; 
    pPIT_Config0->bTimerEn          = TRUE;

    PIT_Init(PIT_CHANNEL0, pPIT_Config0);  
    PIT_SetCallback(PIT_CHANNEL0, Pit0CallBack);

   	EnableInterrupts;
    
    while(1)
    {
        if (DemoState == DemoMMA8451)
        {
            AccelDemo();
        }
        else
        {

        }
    }   
}

